package net.wanglu.www.spdr.filter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

import net.wanglu.www.spdr.rule.Rule;

import org.htmlparser.NodeFilter;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.HasParentFilter;
import org.htmlparser.filters.TagNameFilter;

public class GuardianNodeFilterFactory extends NodeFilterFactory {

	private NodeFilter createNodeFilderByAttribute(String attributeName,
			String attributeValue) throws Exception {
		// TODO Auto-generated method stub
		return new HasAttributeFilter(attributeName, attributeValue);
	}

	private NodeFilter createNodeFilderByName(String tagName) throws Exception {
		// TODO Auto-generated method stub
		return new TagNameFilter(tagName);
	}

	private NodeFilter createNodeFilderByGroup(HashMap<String, String> rule)
			throws Exception {
		// TODO Auto-generated method stub
		TreeMap<String, String> tm = new TreeMap<String, String>(rule);
		String fatherKey = tm.firstKey();
		String sonKey = tm.lastKey();
		
		String father = fatherKey.substring(1);
		String son = sonKey.substring(1);
		
		NodeFilter fatherFilter = null, sonFilter = null, whoseFatherFilter = null;
		if ( father.equalsIgnoreCase(Rule.ELEMENT_NAME)) {
			fatherFilter = this.createNodeFilderByName(tm.get(fatherKey));
		} else {
			fatherFilter = this.createNodeFilderByAttribute(father, tm.get(fatherKey));
		}
		if (son.equalsIgnoreCase(Rule.ELEMENT_NAME)) {
			sonFilter = this.createNodeFilderByName(tm.get(sonKey));
		} else {
			sonFilter = this.createNodeFilderByAttribute(son, tm.get(sonKey));
		}
		
		whoseFatherFilter = new HasParentFilter(fatherFilter);
		
		return new AndFilter(whoseFatherFilter, sonFilter);
	}

	@Override
	public NodeFilter createNodeFilder(HashMap<String, String> rule)
			throws Exception {
		// TODO Auto-generated method stub
		if ( rule == null) return null;
		
		if ( rule.size() == 2) {
			return this.createNodeFilderByGroup(rule);
		} else if ( rule.size() == 1 ) {
			Set<String> keys = rule.keySet();
			Iterator<String> itr = keys.iterator(); 
			if ( itr.hasNext() ) {
				String key = itr.next();
				String value = rule.get(key);
				if ( key.equalsIgnoreCase(Rule.ELEMENT_NAME)) {
					return this.createNodeFilderByName(value);
				} else {
					return this.createNodeFilderByAttribute(key, value);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}
